package org.imlinker.plugin;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;

import org.imlinker.core.Core;
import org.jivesoftware.smack.XMPPConnection;

public class PluginManager {

	public PluginManager(final XMPPConnection connection, final String paraPath) {
		this.path = paraPath;

		ResourceManager.setPath(paraPath);
		ResourceManager.setConnection(connection);
	}

	public ArrayList<String> getNameList() {
		return infoList;
	}

	/**
	 * 初始化，把plugin/文件夹里的插件导入到plugin列表里.
	 */
	public void initial() {

		File pluginDir = new File(path + File.separator + "plugin");

		// 确定文件夹没有错
		if (pluginDir != null && pluginDir.isDirectory()) {
			File[] files = pluginDir.listFiles();
			for (File f : files) {
				// 跳过非.jar文件
				String name = f.getName();
				if (!name.endsWith(".jar")) {
					continue;
				}

				infoList.add(name.substring(0, name.length() - 4));
			}
		}

		for (String name : infoList) {
			// 判断是否启用插件

			String url = "plugin." + name + ".able";
			// 第一次探测到，则不启用
			if (Core.getValue(url) == null) {
				Core.setValueAt(url, "false");
			} else if (Core.getBooleanAt(url)) {
				try {
					Class<?> pluginClass = Class.forName("org.imlinker.plugin."
							+ name);

					System.out.println("/org/imlinker/plugin/"
							+ name.toLowerCase() + "/logo.png");
					URL logoURL = pluginClass
							.getResource("/org/imlinker/plugin/"
									+ name.toLowerCase() + "/logo.png");
					ImageIcon pluginLogo = null;
					if (logoURL != null) {
						pluginLogo = new ImageIcon(logoURL);
					}

					System.out.println(logoURL);
					System.out.println(pluginLogo);
					displayList.addElement(new PluginItem(pluginLogo, name,
							pluginClass));
				} catch (ClassNotFoundException e) {
					System.out.println("Plugin:" + name + " failed");
				}
			}
		}
		Core.save();

	}

	public void setList(final DefaultListModel pluginList) {
		this.displayList = pluginList;

		initial();
	}

	private DefaultListModel displayList;

	private ArrayList<String> infoList = new ArrayList<String>();

	private String path;

}
